package com.zsk.shop.service.yulink;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.constant.Constant;
import com.zsk.shop.common.utils.HttpContext;
import com.zsk.shop.common.utils.HttpUtil;
import com.zsk.shop.entity.yulink.YlUser;
import com.zsk.shop.mapper.YlUserMapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ljh
 * @create 2022/2/22 14:54
 */
@Service
@DS("yulink")
public class YlUserService extends ServiceImpl<YlUserMapper, YlUser> {

    private static final Logger logger = LoggerFactory.getLogger(YlUserService.class);

    public YlUser queryTrueUserByPhone(String phone) {
        LambdaQueryWrapper<YlUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YlUser::getPhone, phone);
        queryWrapper.eq(YlUser::getIsDeleted, false);
        queryWrapper.eq(YlUser::getIsInvalid, false);
        queryWrapper.eq(YlUser::getIsLogout, false);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    public void addUser(String phone, String avatar, String name, String userNo) {
        String host;
        if (Constant.isLocal()) {
            host = "http://localhost:8080";
        } else if (Constant.isDev()) {
            host = "https://apidev.chn-yulink.com";
        } else if (Constant.isTest()) {
            host = "https://apitest.chn-yulink.com";
        } else if (Constant.isProd()) {
            host = "https://api.chn-yulink.com";
        } else {
            return;
        }
        String path = "/base/shopInsertUser.do";
        String method = "GET";
        Map<String, String> headers = new HashMap<>(1);
        headers.put("Authorization", HttpContext.getToken());
        Map<String, String> querys = new HashMap<>(3);
        querys.put("phone", phone);
        querys.put("avatar", avatar);
        querys.put("name", name);
        querys.put("userNo", userNo);
        try {
            HttpResponse response = HttpUtil.doGet(host, path, method, headers, querys);
            //获取response的body
            String json = EntityUtils.toString(response.getEntity());
            logger.info(JSON.toJSONString(json));
            return;
        } catch (Exception e) {
            logger.info(e.getMessage());
            return;
        }
    }

    public YlUser queryByUserNo(String userNo) {
        LambdaQueryWrapper<YlUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YlUser::getUserNo, userNo);
        queryWrapper.last("limit 1");
        return getOne(queryWrapper);
    }

}
